function demodulated_bits = demodulate_data(baseband_signal, M)
% demodulate_data - 将基带信号解调为比特流
%
% 输入参数:
%   baseband_signal - 基带接收信号
%   M               - 调制阶数 (如：2-BPSK, 4-QPSK, 16-16QAM等)
%
% 输出参数:
%   demodulated_bits - 解调后的比特流

% 根据调制方式选择解调方法
switch M
    case 2  % BPSK解调
        % 实部大于0判决为1，小于0判决为0
        demodulated_bits = real(baseband_signal) > 0;
        
    case 4  % QPSK解调
        % 创建QPSK星座图
        constellation = [-1-1i, -1+1i, 1-1i, 1+1i] / sqrt(2);
        
        % 对每个接收符号，找到最近的星座点
        demodulated_symbols = zeros(size(baseband_signal));
        bits_per_symbol = log2(M);
        
        for i = 1:length(baseband_signal)
            % 计算接收符号与每个星座点的欧氏距离
            [~, idx] = min(abs(baseband_signal(i) - constellation));
            demodulated_symbols(i) = idx - 1;  % 索引从1开始，但符号从0开始
        end
        
        % 将符号转换为比特
        demodulated_bits = zeros(1, length(demodulated_symbols) * bits_per_symbol);
        for i = 1:length(demodulated_symbols)
            % 将十进制符号转换为比特
            bit_seq = de2bi(demodulated_symbols(i), bits_per_symbol, 'left-msb');
            demodulated_bits((i-1)*bits_per_symbol+1:i*bits_per_symbol) = bit_seq;
        end
        
    case 16  % 16QAM解调
        % 创建16QAM星座图
        constellation = zeros(16,1);
        for i = 0:15
            % 使用与调制相同的格雷码映射
            b = de2bi(i, 4);
            
            % 计算实部和虚部
            real_part = 2*(1-b(1)) - 1;
            if b(2) == 0
                real_part = real_part * 3;
            end
            
            imag_part = 2*(1-b(3)) - 1;
            if b(4) == 0
                imag_part = imag_part * 3;
            end
            
            constellation(i+1) = (real_part + 1i*imag_part) / sqrt(10);
        end
        
        % 对每个接收符号，找到最近的星座点
        demodulated_symbols = zeros(size(baseband_signal));
        bits_per_symbol = log2(M);
        
        for i = 1:length(baseband_signal)
            % 计算接收符号与每个星座点的欧氏距离
            [~, idx] = min(abs(baseband_signal(i) - constellation));
            demodulated_symbols(i) = idx - 1;
        end
        
        % 将符号转换为比特
        demodulated_bits = zeros(1, length(demodulated_symbols) * bits_per_symbol);
        for i = 1:length(demodulated_symbols)
            % 将十进制符号转换为比特
            bit_seq = de2bi(demodulated_symbols(i), bits_per_symbol, 'left-msb');
            demodulated_bits((i-1)*bits_per_symbol+1:i*bits_per_symbol) = bit_seq;
        end
        
    otherwise
        error('不支持的调制方式: M = %d', M);
end

end 